﻿using CWCS.BLL.WebsocketCommon;
using CWCS.Common.Log;
using CWCS.Core.Library.PLCManager;
using CWCS.Core.Library.ModbusManager;
using CWCS.DataAccess;
using CWCS.Entity;
using CWCS.Entity.Robot;
using CWCS.Entity.SRM;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.IO;
using System.Linq;
using System.Text;
using static CWCS.Entity.Robot.RobotInfo;
using System.Threading.Tasks;

namespace CWCS.BLL
{
    public class RobotBLL : BLLBase
    {
        private LogHelper robotlog;
        private LogHelper robotConnectlog;
        private RobotPLC robotPLC;
        //private RobotModus robotmPLC;

        private ConveryBLL sta_bll;

        private List<RobotInfo> lstRb;
        private string mes_site = string.Empty;
        private string operation_revision = string.Empty;
        private string mes_resource = string.Empty;
        private string _gongyiID = string.Empty;
        private string mesuser = string.Empty;
        private string strid = string.Empty;
        private bool _ExecuteResult = false;
        private bool _bCheck = false;
        private bool _check_flag = false;
        private bool _heat_flag = false;
        private bool flag = false;
        private bool _inplace_flag = false;
        string firstItembarcode = string.Empty;
        private bool _pick_flag = false;
        private bool _complete_flag = false;
        // ConveryModbus converyPLC = new ConveryModbus();
        ConveryPLC converyPLC = new ConveryPLC();
        private string _showMsg = string.Empty;
        private int result = 0;
        private int icount = 0;
        private string plcinfo = string.Empty;
        private string plcmsg = string.Empty;
        private Dictionary<string, string> FirstItemcodeInfo = new Dictionary<string, string>();
        private Dictionary<string, string> RobotAlarm = new Dictionary<string, string>();

        string checkStatus = ConfigurationManager.AppSettings["CheckStatus"].ToString().Trim();
        #region event
        public delegate void ShowMessage(string type, string msg);
        public event ShowMessage ShowRBMsg;

        public delegate void NotiftyStatus(RobotInfo rbinfo);
        public event NotiftyStatus ShowRbStatus;
        private delegate void DoTask(RobotInfo rbinfo);
        private DoTask DoRobotTask;
        #endregion

        public RobotBLL()
        {
            robotlog = new LogHelper("Robot");
            robotConnectlog = new LogHelper("RobotConnect");
            robotPLC = new RobotPLC();
            sta_bll = new ConveryBLL();
            this.DoRobotTask += new DoTask(Process);
        }

        private bool InitRobot()
        {
            try
            {
                DataTable dt = GetRBEquipment();
                lstRb = ConvertToList(dt);
                string error = "";
                if (lstRb.Count > 0)
                {
                    robotPLC.InitData(lstRb, ref error);
                    ShowRobotMsg("Msg", "机械系统初始化完成!");
                    return true;
                }
                else
                    ShowRobotMsg("Msg", "加载组盘机械数据时,未找到相关数据！");
            }
            catch (Exception ex)
            {

            }
            return false;
        }
        public void Start()
        {
            try
            {
                robotPLC.GetTaskInfo += new PLCHelper.GetPLCTaskInfo(DoWork);
                robotPLC.ShowMessage += new PLCHelper.ShowPLCMessage(ShowRobotMsg);
                robotPLC.ShowStatus += new PLCHelper.ShowEquipmentStatus(ShowRobotStatus);

                if (InitRobot())
                {
                    for (int i = 1; i < 4; i++)
                    {
                        robotPLC.Run(i);
                    }
                }
                //robotPLC.Run(1);

                if (File.Exists(".\\RobotAlarm.txt"))
                {
                    FileStream fs = new FileStream(".\\RobotAlarm.txt", FileMode.Open, FileAccess.Read);
                    StreamReader sr = new StreamReader(fs);
                    string strline = sr.ReadToEnd();
                    string[] msg = strline.Split(new char[] { ';' });
                    string[] msg2;
                    for (int i = 0; i < msg.Length; i++)
                    {
                        msg2 = msg[i].Split(new char[] { ',' });
                        if (msg2.Length > 1 && !RobotAlarm.ContainsKey(msg2[0]))
                            RobotAlarm.Add(msg2[0].Trim(), msg2[1].Trim());
                    }
                }
            }
            catch (Exception ex)
            {
                ShowRobotMsg("Connect", "初始化异常:" + ex.Message);
            }
        }

        private DataTable GetRBEquipment()
        {
            try
            {
                DataTable dt = new DataTable();
                DataSet ds = DataAccessFactory.Instance.ExecuteDataSet("select * from WCS_OPCItem where groupname='Robot' and areacode='" + AreaCode + "-" + LineCode + "-" + ZoneCode + "' and status='1' order by stationno ", CommandType.Text, null);
                if (ds != null && ds.Tables.Count > 0)
                    dt = ds.Tables[0];

                return dt;
            }
            catch (Exception ex)
            {
                return null;
            }
        }

        private List<RobotInfo> ConvertToList(DataTable dt)
        {
            if (dt == null || dt.Rows.Count <= 0)
                throw new Exception("加载数据异常！");
            List<RobotInfo> lst = new List<RobotInfo>();
            foreach (DataRow dr in dt.Rows)
            {
                RobotInfo ci = new RobotInfo();
                ci.robotnum = dr["stationno"].ToString();//机械手编号
                ci.name = dr["itemname"].ToString();//机械手编号
                ci.stationno = dr["field1"].ToString();
                ci.stationtype = int.Parse(dr["stationtype"].ToString());
                ci.key_ip = dr["userid"].ToString();
                ci.DBAddress = int.Parse(dr["objects"].ToString());
                ci.length = int.Parse(dr["signaltype"].ToString());
                ci.start = int.Parse(dr["value"].ToString());
                ci.zonecode = dr["ZONE"].ToString();//拆盘机械手2号工位站台
                ci.ZoneId = dr["field4"].ToString();
                ci.cellNum = int.Parse(dr["field5"].ToString());
                ci.technologycode = dr["field3"].ToString();
                ci.relaseMode = dr["field2"].ToString();
                ci.belong = dr["belong"].ToString();
                ci.robotName = dr["remark"].ToString();
                ci.beginvale = int.Parse(dr["beginvale"].ToString());
                if (ci.stationtype == 5)
                {
                    string[] RobotPutStation = dr["field2"].ToString().Split(new char[] { ',' });
                    for (int i = 0; i < RobotPutStation.Length; i++)
                    {
                        if (RobotPutStation[i].Length == 4)
                        {
                            ci.lstStation.Add(RobotPutStation[i]);
                        }
                    }
                }
                lst.Add(ci);
            }
            return lst;
        }

        private void DoWork(object obj)
        {
            if (obj != null)
            {
                if (obj is RobotInfo)
                {
                    RobotInfo rb = (RobotInfo)obj;
                    Process(rb);
                }
            }
        }
        //宁德
        private void Process(RobotInfo rb)
        {
            if (DoRobotTask != null)
            {
                if (rb.stationtype == 2 || rb.stationtype == 4)//组盘业务处理
                {
                    Put(rb);
                }
                else if (rb.stationtype == 3)//拆盘业务处理
                {
                    Pick(rb);
                }
                else if (rb.stationtype == 1 || rb.stationtype == 5)//扫码校验处理
                {
                    Check(rb);
                }
                else if (rb.stationtype == 6)//码垛业务处理
                {
                    Stacking(rb);
                }
            }
        }
        /// <summary>
        ///  调用电芯MES校验接口
        /// </summary>
        /// <param name="barcode"></param>
        /// <param name="mes_site"></param>
        /// <returns></returns>
        private bool ANDcell_check(RobotInfo rb, string barcode, ref string strid)
        {
            if (!barcode.Contains("ERROR"))// && barcode.Length == 24)
            {
                if (!GetGongYi(rb.stationno.Trim(), rb.ZoneId, "FittingCheckForCell", LineCode, ref mes_site, ref operation_revision, ref mes_resource, ref mesuser, ref _gongyiID))
                {
                    _showMsg = string.Format("机器手:{0},未设置item_itemgongyi工艺参数,电芯条码:{1}", rb.robotnum + rb.robotName, barcode);
                    ShowRobotMsg("Info", _showMsg);
                }
                else
                {
                    _showMsg = string.Format("机器手:{0},判断条码,电芯条码:{1}", rb.robotnum + rb.robotName, barcode);
                    _bCheck = AddJK_CellInfo(rb.ZoneId, rb.zonecode, "", _gongyiID, "0", "FittingCheckForCell", "MES", "WCS", "1", mes_site, operation_revision, mes_resource, barcode, "", "COLUMN-FIRST", "", mesuser, ref strid);
                    _showMsg = string.Format("机器手:{0},第一次调用MES合法性校验接口:{1},电芯条码:{2}", rb.robotnum + rb.robotName, _bCheck ? "成功" : "失败", barcode);
                    ShowRobotMsg("Info", _showMsg);
                    return _bCheck;
                }
            }
            else
            {
                _showMsg = string.Format("机器手:{0},电池扫码器读取到ERROR电芯条码或长度不合法:{1}", rb.robotnum + rb.robotName, barcode);
                ShowRobotMsg("Info", _showMsg);
                return false;
            }
            return true;
        }

        private bool ANDcell_InStationCheck(RobotInfo rb, string barcode, ref string strincheckid)
        {
            if (!barcode.Contains("ERROR"))// && barcode.Length == 24)
            {
                if (!GetGongYi(rb.stationno.Trim(), rb.ZoneId, "InStationCheck", LineCode, ref mes_site, ref operation_revision, ref mes_resource, ref mesuser, ref _gongyiID))
                {
                    _showMsg = string.Format("机器手:{0},未设置item_itemgongyi表的InStationCheck工艺参数,电芯条码:{1}", rb.robotnum + rb.robotName, barcode);
                    ShowRobotMsg("Info", _showMsg);
                }
                else
                {
                    _showMsg = string.Format("机器手:{0},判断条码,电芯条码:{1}", rb.robotnum + rb.robotName, barcode);
                    _bCheck = AddJK_CellInfo(rb.ZoneId, rb.zonecode, "", _gongyiID, "0", "InStationCheck", "MES", "WCS", "1", mes_site, operation_revision, mes_resource, barcode, "", "COLUMN-FIRST", "1", mesuser, ref strincheckid);
                    _showMsg = string.Format("机器手:{0},第一次调用MES的InStationCheck进账接口:{1},电芯条码:{2}", rb.robotnum + rb.robotName, _bCheck ? "成功" : "失败", barcode);
                    ShowRobotMsg("Info", _showMsg);
                    return _bCheck;
                }
            }
            else
            {
                _showMsg = string.Format("机器手:{0},电池扫码器读取到ERROR电芯条码或长度不合法:{1}", rb.robotnum + rb.robotName, barcode);
                ShowRobotMsg("Info", _showMsg);
                return false;
            }
            return true;
        }

        /// <summary>
        ///  校验电芯OK/NG
        /// </summary>
        /// <param name="rb"></param>
        /// <param name="itembarcode">电芯条码</param>
        /// <param name="count">校验电芯位置</param>
        /// <returns></returns>
        private bool Checkbarcodereading_check(RobotInfo rb, string itembarcode, string count, string barcode, ref string TaskInfo, ref string strid1, ref string strincheckid1)
        {
            string TaskInfo1 = "0";
            string TaskInfo2 = "0";
            TaskInfo = "0";
            bool b_flag1 = false;
            string message = "";
            if (itembarcode.Contains("ERROR") || itembarcode.Length < 6)
            {
                ShowRobotMsg("Info", string.Format("机械手:{0},到位申请{1}号位,电芯:{2},条码ERROR或长度小于24,被NG处理", rb.robotnum + rb.robotName, count, itembarcode));
                TaskInfo = "2";
                b_flag1 = true;
            }
            else
            {
                if (itembarcode != "\0\0\0\0\0\0\0\0\0\0\0\0" && itembarcode != "000000000001")
                {
                    if (checkExists(itembarcode) > 0)
                    {
                        TaskInfo = "2";
                        ShowRobotMsg("Info", string.Format("机械手:{0},到位申请{1}号位,电芯:{2},检测到重码", rb.robotnum + rb.robotName, count, itembarcode));
                        b_flag1 = true;
                    }
                    else
                    {
                        if (MESStatus == "1")//MES开启情况下添加MES接口组盘信息
                        {
                            bool flag = false;
                            string result = CheckExistsCell(ref flag, ref strid1, ref message, WareHouseID, "", "FittingCheckForCell", itembarcode);
                            if (!flag)//提示错误
                            {
                                if (ANDcell_check(rb, itembarcode, ref strid1))
                                {
                                    ShowRobotMsg("Info", string.Format("机械手:{0},到位申请{1}号位,电芯:{2},第二次调用MES合法性校验接口成功", rb.robotnum + rb.robotName, count, itembarcode));
                                    //return false;
                                }
                                else
                                {
                                    TaskInfo1 = "2";
                                    ShowRobotMsg("Info", string.Format("机械手:{0},到位申请{1}号位,电芯:{2},第二次调用MES合法性校验接口失败", rb.robotnum + rb.robotName, count, itembarcode));
                                    b_flag1 = true;
                                }
                            }
                            else
                            {
                                if (string.IsNullOrEmpty(result))
                                {
                                    ShowRobotMsg("Info", string.Format("机械手:{0},到位申请{1}号位,电芯:{2},等待mes校验返回结果", rb.robotnum + rb.robotName, count, itembarcode));
                                    return false;
                                }
                                if (result == "0")
                                {
                                    TaskInfo1 = "1";
                                    ShowRobotMsg("Info", string.Format("机械手:{0},到位申请{1}号位,电芯1:{2},MES校验合法！", rb.robotnum + rb.robotName, count, itembarcode));
                                    b_flag1 = true;
                                }
                                else
                                {
                                    TaskInfo1 = "2";
                                    ShowRobotMsg("Info", string.Format("机械手:{0},到位申请{1}号位,电芯:{2},MES校验NG:{3}！", rb.robotnum + rb.robotName, count, itembarcode, message));
                                    b_flag1 = true;
                                }
                            }
                            string result_incheck = CheckExistsCell(ref flag, ref strincheckid1, ref message, WareHouseID, "", "InStationCheck", itembarcode);
                            if (!flag)//提示错误
                            {
                                if (ANDcell_InStationCheck(rb, itembarcode, ref strincheckid1))
                                {
                                    ShowRobotMsg("Info", string.Format("机械手:{0},到位申请{1}号位,电芯:{2},第二次调用MES的InStationCheck校验接口成功", rb.robotnum + rb.robotName, count, itembarcode));
                                    return false;
                                }
                                else
                                {
                                    TaskInfo2 = "2";
                                    ShowRobotMsg("Info", string.Format("机械手:{0},到位申请{1}号位,电芯:{2},第二次调用MES的InStationCheck校验接口失败", rb.robotnum + rb.robotName, count, itembarcode));
                                    b_flag1 = true;
                                }
                            }
                            else
                            {
                                if (string.IsNullOrEmpty(result_incheck))
                                {
                                    ShowRobotMsg("Info", string.Format("机械手:{0},到位申请{1}号位,电芯:{2},等待mes的InStationCheck校验返回结果", rb.robotnum + rb.robotName, count, itembarcode));
                                    return false;
                                }
                                if (result_incheck == "0")
                                {
                                    TaskInfo2 = "1";
                                    ShowRobotMsg("Info", string.Format("机械手:{0},到位申请{1}号位,电芯1:{2},MES的InStationCheck校验合法！", rb.robotnum + rb.robotName, count, itembarcode));
                                    b_flag1 = true;
                                }
                                else
                                {
                                    TaskInfo2 = "2";
                                    ShowRobotMsg("Info", string.Format("机械手:{0},到位申请{1}号位,电芯:{2},MES的InStationCheck校验NG:{3}！", rb.robotnum + rb.robotName, count, itembarcode, message));
                                    b_flag1 = true;
                                }
                            }

                            if (TaskInfo1 == "1" && TaskInfo2 == "1")
                                TaskInfo = "1";
                            else
                                TaskInfo = "2";//如果校验接口与入库校验接口都OK，判断OK，其它判定NG
                        }
                        else
                        {
                            TaskInfo = "1";
                            ShowRobotMsg("Info", string.Format("机械手:{0},到位申请{1}号位,电芯:{2},MES未开启WMS校验合法！", rb.robotnum + rb.robotName, count, itembarcode));
                            b_flag1 = true;
                        }
                    }
                }
                else
                {
                    TaskInfo = "2";
                    ShowRobotMsg("Info", string.Format("机械手:{0},到位申请器{1}号位,电芯:{2}读到错误条码", rb.robotnum + rb.robotName, count, itembarcode));
                    b_flag1 = true;
                }
            }
            return b_flag1;
        }
        /// <summary>
        ///  调用托盘分档等级接口
        /// </summary>
        /// <param name="barcode"></param>
        /// <param name="mes_site"></param>
        /// <returns></returns>
        private bool AddTrayGradeInterface(RobotInfo rb, string barcode, ref string strid)
        {
            if (!barcode.Contains("ERROR") && barcode.Length == 9)
            {
                if (!GetGongYi(rb.stationno.Trim(), rb.ZoneId, "GetTrayGrade", LineCode, ref mes_site, ref operation_revision, ref mes_resource, ref mesuser, ref _gongyiID))
                {
                    _showMsg = string.Format("机器手:{0},未设置item_itemgongyi工艺参数,电芯条码:{1}", rb.robotnum + rb.robotName, barcode);
                    ShowRobotMsg("Info", _showMsg);
                }
                else
                {
                    _showMsg = string.Format("机器手:{0},判断条码,电芯条码:{1}", rb.robotnum + rb.robotName, barcode);
                    _bCheck = AddJK_CellInfo(rb.ZoneId, rb.zonecode, barcode, _gongyiID, "0", "GetTrayGrade", "MES", "WCS", "1", mes_site, operation_revision, mes_resource,"", "", "COLUMN-FIRST", "", mesuser, ref strid);
                    _showMsg = string.Format("机器手:{0},第一次调用MES托盘分档接口:{1},电芯条码:{2}", rb.robotnum + rb.robotName, _bCheck ? "成功" : "失败", barcode);
                    ShowRobotMsg("Info", _showMsg);
                    return _bCheck;
                }
            }
            else
            {
                _showMsg = string.Format("机器手:{0},托盘扫码器读取到ERROR电芯条码或长度不合法:{1}", rb.robotnum + rb.robotName, barcode);
                ShowRobotMsg("Info", _showMsg);
                return false;
            }
            return true;
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="rb"></param>
        /// <param name="itembarcode"></param>
        /// <param name="count"></param>
        /// <param name="barcode"></param>
        /// <param name="TaskInfo"></param>
        /// <param name="strid1"></param>
        /// <param name="strincheckid1"></param>
        /// <returns></returns>
        private bool CheckTrayGrade(RobotInfo rb, string count, string barcode, ref string TaskInfo, ref string strid1)
        {
            TaskInfo = "0";
            bool b_flag1 = false;
            string message = "";
            string level = "";
            int levelcount = 0;
            levelcount = CheckTrayGradeLevelCount(barcode, ref level);
            if (barcode.Contains("ERROR") || barcode.Length < 9)
            {
                ShowRobotMsg("Info", string.Format("机械手:{0},到位申请{1}号位,托盘:{2},条码ERROR或长度{3}小于9,被NG处理", rb.robotnum + rb.robotName, count, barcode, barcode.Length));
                b_flag1 = false;
            }
            else
            {
                if (barcode != "\0\0\0\0\0\0\0\0\0\0\0\0" && barcode != "000000000001")
                {
                    if (levelcount == 0)
                    {
                        bool flag = false;
                        string result = CheckExistsBarCode(ref flag, ref strid1, ref message, "", "GetTrayGrade", barcode);
                        if (flag)
                        {
                            ShowRobotMsg("Info", string.Format("机械手:{0},到位申请{1}号位,托盘:{2},获取MES托盘分档失败:{3},接口结果:{4}！", rb.robotnum + rb.robotName, count, barcode, message, result));
                        }
                        else
                        {
                            ShowRobotMsg("Info", string.Format("机械手:{0},到位申请{1}号位,托盘条码:{2},未调用MES托盘分档接口", rb.robotnum + rb.robotName, count, barcode, CheckTrayGradeLevelCount(barcode, ref level)));
                        }
                        b_flag1 = false;
                    }
                    else if (levelcount == 1)
                    {
                        if (MESStatus == "1")//MES开启情况下添加MES分档接口信息
                        {
                            bool flag = false;
                            string result = CheckExistsBarCode(ref flag, ref strid1, ref message, "", "GetTrayGrade", barcode);
                            if (!flag)//提示错误
                            {
                                if (AddTrayGradeInterface(rb, barcode, ref strid1))
                                {
                                    ShowRobotMsg("Info", string.Format("机械手:{0},到位申请{1}号位,托盘:{2},第二次调用MES托盘分档接口成功", rb.robotnum + rb.robotName, count, barcode));
                                    return false;
                                }
                                else
                                {
                                    ShowRobotMsg("Info", string.Format("机械手:{0},到位申请{1}号位,托盘:{2},第二次调用MES托盘分档接口失败", rb.robotnum + rb.robotName, count, barcode));
                                    b_flag1 = false;
                                }
                            }
                            else
                            {
                                if (string.IsNullOrEmpty(result))
                                {
                                    ShowRobotMsg("Info", string.Format("机械手:{0},到位申请{1}号位,托盘:{2},等待mes托盘分档返回结果", rb.robotnum + rb.robotName, count, barcode));
                                    return false;
                                }
                                if (result == "0")
                                {
                                    switch (level)
                                    {
                                        case "Marking":
                                            TaskInfo = "1";
                                            break;
                                        case "marking":
                                            TaskInfo = "1";
                                            break;
                                        case "N":
                                            TaskInfo = "2";
                                            break;
                                        case "L":
                                            TaskInfo = "3";
                                            break;
                                        case "M":
                                            TaskInfo = "5";
                                            break;
                                    }
                                    ShowRobotMsg("Info", string.Format("机械手:{0},到位申请{1}号位,托盘1:{2},档位:{3},下发档位信息:{4}获取MES托盘分档成功！", rb.robotnum + rb.robotName, count, barcode, level, TaskInfo));
                                    b_flag1 = true;
                                }
                                else
                                {
                                    ShowRobotMsg("Info", string.Format("机械手:{0},到位申请{1}号位,托盘:{2},获取MES托盘分档失败:{3}！", rb.robotnum + rb.robotName, count, barcode, message));
                                    b_flag1 = false;
                                }
                            }
                        }
                        else
                        {
                            TaskInfo = "1";
                            ShowRobotMsg("Info", string.Format("机械手:{0},到位申请{1}号位,电芯:{2},MES未开启WMS校验合法！", rb.robotnum + rb.robotName, count, barcode));
                            b_flag1 = true;
                        }
                    }
                    else
                    {
                        ShowRobotMsg("Info", string.Format("机械手:{0},到位申请{1}号位,托盘条码:{2},检测到{3}种分档等级", rb.robotnum + rb.robotName, count, barcode, CheckTrayGradeLevelCount(barcode, ref level)));
                        b_flag1 = false;
                    }
                }
                else
                {
                    TaskInfo = "2";
                    ShowRobotMsg("Info", string.Format("机械手:{0},到位申请器{1}号位,托盘:{2}读到错误条码", rb.robotnum + rb.robotName, count, barcode));
                    b_flag1 = true;
                }
            }
            return b_flag1;
        }

        /// <summary>
        /// 扫码业务处理
        /// </summary>
        /// <param name="rb"></param>
        private void Check(RobotInfo rb)
        {
            try
            {
                string[] TaskInfo = new string[5] { "0", "0", "0", "0", "0" };
                RobotCommand cmd = RobotCommand.None;
                bool b_flag1 = false;
                bool b_flag2 = false;
                bool b_flag3 = false;
                bool b_flag4 = false;
                bool check1_flag = false;
                bool check2_flag = false;
                bool check3_flag = false;
                bool check4_flag = false;
                string strid1 = "";
                string strid2 = "";
                string strid3 = "";
                string strid4 = "";
                string strincheckid1 = "";
                string strincheckid2 = "";
                string strincheckid3 = "";
                string strincheckid4 = "";
                string fristItemcode = string.Empty;
                int index = 12;
                if (barcodeCheck.Equals("1"))
                {
                    CheckCellType(rb.robotnum);
                    if (celllen < 1) celllen = 30;
                }
                else
                {//不开启条码校验时,条码长度和电控最长保持一致
                    celllen = 30;
                }
                if (rb.rbstate == 3)
                {
                    string message = rb.rbstate == 3 ? "故障" : "手动";
                    QueueSpeech.AddQueue("机械手扫码枪" + rb.stationno + "站台" + message);
                }
                #region 扫码申请
                if (rb.inplacebarcodereading == 1 && rb.rbstate == 1)
                {
                    _inplace_flag = false;
                    ShowRobotMsg("Info", string.Format("机械手:{0},申请条码校验，条码1为：{1}！", rb.robotnum + rb.robotName, rb.barcode1));
                    ShowRobotMsg("Info", string.Format("机械手:{0},申请条码校验，条码2为：{1}！", rb.robotnum + rb.robotName, rb.barcode2));
                    if (rb.barcode1 == "ERROR" || rb.barcode1.Equals("") || string.IsNullOrEmpty(rb.barcode1) || rb.barcode1.Length < 12)
                    {
                        TaskInfo[1] = "2";
                        check1_flag = true;
                        ShowRobotMsg("Info", string.Format("机械手:{0},申请条码校验，条码非法，为：{1}！", rb.robotnum + rb.robotName, rb.barcode1));
                    }
                    else
                    {
                        if (ANDcell_check(rb, rb.barcode1, ref strid1) && ANDcell_InStationCheck(rb, rb.barcode1, ref strincheckid1))
                        {
                            TaskInfo[1] = "1";
                            check1_flag = true;
                        }
                        else
                            return;
                    }
                    if (rb.barcode2 == "ERROR" || rb.barcode2.Equals("") || string.IsNullOrEmpty(rb.barcode2) || rb.barcode2.Length < 12)
                    {
                        TaskInfo[2] = "2";
                        check2_flag = true;
                        ShowRobotMsg("Info", string.Format("机械手:{0},申请条码校验，条码非法，为：{1}！", rb.robotnum + rb.robotName, rb.barcode2));
                    }
                    else
                    {
                        if (ANDcell_check(rb, rb.barcode2, ref strid2) && ANDcell_InStationCheck(rb, rb.barcode2, ref strincheckid2))
                        {
                            TaskInfo[2] = "1";
                            check2_flag = true;
                        }
                        else
                            return;
                    }
                    if (rb.cellNum == 2)
                    {
                        if (check1_flag && check2_flag)
                        {
                            TaskInfo[0] = "2";
                            _inplace_flag = true;
                        }
                    }
                    if (rb.cellNum == 4)
                    {
                        ShowRobotMsg("Info", string.Format("机械手:{0},申请条码校验，条码3为：{1}！", rb.robotnum + rb.robotName, rb.barcode3));
                        ShowRobotMsg("Info", string.Format("机械手:{0},申请条码校验，条码4为：{1}！", rb.robotnum + rb.robotName, rb.barcode4));
                        if (rb.barcode3 == "ERROR" || rb.barcode3.Equals("") || string.IsNullOrEmpty(rb.barcode3) || rb.barcode3.Length < 12)
                        {
                            TaskInfo[3] = "2";
                            check3_flag = true;
                            ShowRobotMsg("Info", string.Format("机械手:{0},申请条码校验，条码非法，为：{1}！", rb.robotnum + rb.robotName, rb.barcode3));
                        }
                        else
                        {
                            if (ANDcell_check(rb, rb.barcode3, ref strid3) && ANDcell_InStationCheck(rb, rb.barcode3, ref strincheckid3))
                            {
                                TaskInfo[3] = "2";
                                check3_flag = true;
                            }
                            else
                                return;
                        }
                        if (rb.barcode4 == "ERROR" || rb.barcode4.Equals("") || string.IsNullOrEmpty(rb.barcode4) || rb.barcode4.Length < 12)
                        {
                            TaskInfo[4] = "2";
                            check4_flag = true;
                            ShowRobotMsg("Info", string.Format("机械手:{0},申请条码校验，条码非法，为：{1}！", rb.robotnum + rb.robotName, rb.barcode4));
                        }
                        else
                        {
                            if (ANDcell_check(rb, rb.barcode4, ref strid4) && ANDcell_InStationCheck(rb, rb.barcode4, ref strincheckid4))
                            {
                                TaskInfo[4] = "2";
                                check4_flag = true;
                            }
                            else
                                return;
                        }
                        if (check1_flag && check2_flag && check3_flag && check4_flag)
                        {
                            TaskInfo[0] = "2";
                            _inplace_flag = true;
                        }
                    }
                    if (_inplace_flag)
                    {
                        string plcmsg = string.Empty;
                        for (int i = 1; i <= rb.cellNum; i++)
                        {
                            plcmsg += "第" + i + "个电芯的接口处理结果为：" + TaskInfo[i] + ";";
                        }
                        cmd = RobotCommand.InplaceResult;
                        if (WriteRobotInfo("PutRobot", cmd, rb.robotnum.ToString(), TaskInfo, index, rb.cellNum * 2 + 1, rb.cellNum))
                        {
                            ShowRobotMsg("Info", string.Format("机械手:{0},命令:{1}写入成功,数据如下：{2}！", rb.robotnum + rb.robotName, cmd, plcmsg));
                        }
                        else
                        {
                            ShowRobotMsg("Info", string.Format("机械手:{0},命令:{1}写入失败,数据如下：{2}！", rb.robotnum + rb.robotName, cmd, plcmsg));
                        }
                        _inplace_flag = false;
                    }
                }
                #endregion

                #region 一组电芯到位申请
                // if (rb.checkbarcodereading == 3 && rb.rbstate == 1)
                if (rb.checkbarcodereading == 1 && rb.rbstate == 1)
                {
                    ShowRobotMsg("Info", string.Format("机械手:{0},条码到位申请，条码1为：{1}！", rb.robotnum + rb.robotName, rb.barcode1));
                    ShowRobotMsg("Info", string.Format("机械手:{0},条码到位申请，条码2为：{1}！", rb.robotnum + rb.robotName, rb.barcode2));
                    _check_flag = false;
                    if (checkStatus == "1")//判断电芯是否需要开启电芯前13位一致性校验
                    {
                        if (rb.workstation > 0)
                        {
                            rb.traycode = converyPLC.ReadStaInfo(rb.lstStation[rb.workstation - 1])[2].Trim(' ');
                        }
                        #region 判断电芯1与托盘内电芯的前13位是否一致
                        if (rb.traycode.Length > 10)
                        {
                            if (CheckCell(rb, rb.barcode1, "1", rb.traycode, ref TaskInfo[1]))
                            {
                                b_flag1 = true;
                            }
                        }
                        #endregion
                    }
                    if (!b_flag1)
                    {
                        if (Checkbarcodereading_check(rb, rb.barcode1, "1", rb.traycode, ref TaskInfo[1], ref strid1, ref strincheckid1))
                        {
                            b_flag1 = true;
                        }
                    }

                    //校验电池条码2,如果第一个电池未进行校验,则继续等待第一个电池校验后继续
                    if (checkStatus == "1")
                    {
                        #region 判断电芯2与托盘内电芯的前13位是否一致
                        if (rb.traycode.Length > 10)
                        {
                            if (CheckCell(rb, rb.barcode2, "2", rb.traycode, ref TaskInfo[2]))
                            {
                                b_flag2 = true;
                            }
                        }
                        #endregion

                        #region 检测条码2与条码1前13位
                        if (rb.barcode2.Trim(' ').Length > 13)
                        {
                            if (rb.barcode2.Substring(0, 13) != rb.barcode1.Substring(0, 13) && !b_flag1 && !b_flag2)
                            {
                                ShowRobotMsg("Info", string.Format("机械手:{0},到位申请电芯2:{1}与电芯1:{2}前13位不一致.该电芯当NG处理", rb.robotnum + rb.robotName, rb.barcode2, rb.barcode1));
                                TaskInfo[2] = "2";
                                b_flag2 = true;
                            }
                        }
                        #endregion
                    }
                    if (!b_flag2)
                    {
                        if (Checkbarcodereading_check(rb, rb.barcode2, "2", rb.traycode, ref TaskInfo[2], ref strid2, ref strincheckid2))
                        {
                            b_flag2 = true;
                        }
                    }
                    if (rb.cellNum == 2)
                    {
                        if (b_flag1 && b_flag2)
                        {
                            if (rb.barcode2 == rb.barcode1 && rb.barcode1.Length >= 24 && rb.barcode2.Length >= 24)
                            {
                                ShowRobotMsg("Info", string.Format("机械手:{0},到位申请电芯1:{1},电芯2:{2}有多个条码一致.都当NG处理", rb.robotnum + rb.robotName, rb.barcode1, rb.barcode2));
                                TaskInfo[1] = "2";
                                TaskInfo[2] = "2";
                            }
                            index = 12;
                            DeleteJK_NAME(strid1);
                            DeleteJK_NAME(strid2);
                            ShowRobotMsg("Info", string.Format("机械手:{0},电芯1:{1}到位申请完成,清除校验接口记录", rb.robotnum + rb.robotName, rb.barcode1));
                            ShowRobotMsg("Info", string.Format("机械手:{0},电芯2:{1}到位申请完成,清除校验接口记录", rb.robotnum + rb.robotName, rb.barcode2));
                            DeleteJK_NAME(strincheckid1);
                            DeleteJK_NAME(strincheckid2);
                            ShowRobotMsg("Info", string.Format("机械手:{0},电芯1:{1}到位申请完成,清除Incheck校验接口记录", rb.robotnum + rb.robotName, rb.barcode1));
                            ShowRobotMsg("Info", string.Format("机械手:{0},电芯2:{1}到位申请完成,清除Incheck校验接口记录", rb.robotnum + rb.robotName, rb.barcode2));
                            TaskInfo[0] = "2";
                            cmd = RobotCommand.CheckResult;
                            _check_flag = true;
                        }
                    }
                    if (rb.cellNum == 4)
                    {
                        ShowRobotMsg("Info", string.Format("机械手:{0},条码到位申请，条码3为：{1}！", rb.robotnum + rb.robotName, rb.barcode3));
                        ShowRobotMsg("Info", string.Format("机械手:{0},条码到位申请，条码4为：{1}！", rb.robotnum + rb.robotName, rb.barcode4));
                        if (checkStatus == "1")
                        {
                            #region 判断电芯3与托盘内电芯的前13位是否一致
                            if (rb.traycode.Length > 10)
                            {
                                if (CheckCell(rb, rb.barcode3, "3", rb.traycode, ref TaskInfo[3]))
                                {
                                    b_flag3 = true;
                                }
                            }
                            #endregion

                            #region 检测条码3与条码1前13位
                            if (rb.barcode3.Trim(' ').Length > 13)
                            {
                                if (rb.barcode3.Substring(0, 13) != rb.barcode1.Substring(0, 13) && !b_flag1 && !b_flag3)
                                {
                                    ShowRobotMsg("Info", string.Format("机械手:{0},到位申请电芯3:{1}与电芯1:{2}前13位不一致.该电芯当NG处理", rb.robotnum + rb.robotName, rb.barcode3, rb.barcode1));
                                    TaskInfo[3] = "2";
                                    b_flag3 = true;
                                }
                            }
                            #endregion
                        }
                        if (!b_flag3)
                        {
                            if (Checkbarcodereading_check(rb, rb.barcode3, "3", rb.traycode, ref TaskInfo[3], ref strid3, ref strincheckid3))
                            {
                                b_flag3 = true;
                            }
                        }
                        if (checkStatus == "1")
                        {
                            #region 判断电芯4与托盘内电芯的前13位是否一致
                            if (rb.traycode.Length > 10)
                            {
                                if (CheckCell(rb, rb.barcode4, "4", rb.traycode, ref TaskInfo[4]))
                                {
                                    b_flag4 = true;
                                }
                            }
                            #endregion
                            #region 检测条码4与条码1前13位
                            if (rb.barcode4.Trim(' ').Length > 13)
                            {
                                if (rb.barcode4.Substring(0, 13) != rb.barcode1.Substring(0, 13) && !b_flag1 && !b_flag4)
                                {
                                    ShowRobotMsg("Info", string.Format("机械手:{0},到位申请电芯4:{1}与电芯1:{2}前13位不一致.该电芯当NG处理", rb.robotnum + rb.robotName, rb.barcode4, rb.barcode1));
                                    TaskInfo[4] = "2";
                                    b_flag4 = true;
                                }
                            }
                            #endregion
                        }
                        if (!b_flag4)
                        {
                            if (Checkbarcodereading_check(rb, rb.barcode4, "4", rb.traycode, ref TaskInfo[4], ref strid4, ref strincheckid4))
                            {
                                b_flag4 = true;
                            }
                        }
                        if (b_flag1 && b_flag2 && b_flag3 && b_flag4)
                        {
                            if ((rb.barcode2 == rb.barcode1 || rb.barcode3 == rb.barcode1 || rb.barcode4 == rb.barcode1 || rb.barcode3 == rb.barcode2 || rb.barcode4 == rb.barcode2 || rb.barcode4 == rb.barcode3) &&
                                 rb.barcode1.Length >= 24 && rb.barcode2.Length >= 24 && rb.barcode3.Length >= 24 && rb.barcode4.Length >= 24)
                            {
                                ShowRobotMsg("Info", string.Format("机械手:{0},到位申请电芯1:{1},电芯2:{2},电芯3:{3},电芯4:{4}有多个条码一致.都当NG处理", rb.robotnum + rb.robotName, rb.barcode1, rb.barcode2, rb.barcode3, rb.barcode4));
                                TaskInfo[1] = "2";
                                TaskInfo[2] = "2";
                                TaskInfo[3] = "2";
                                TaskInfo[4] = "2";
                            }

                            DeleteJK_NAME(strid1);
                            DeleteJK_NAME(strid2);
                            ShowRobotMsg("Info", string.Format("机械手:{0},电芯1:{1}到位申请完成,清除校验接口记录", rb.robotnum + rb.robotName, rb.barcode1));
                            ShowRobotMsg("Info", string.Format("机械手:{0},电芯2:{1}到位申请完成,清除校验接口记录", rb.robotnum + rb.robotName, rb.barcode2));
                            DeleteJK_NAME(strincheckid1);
                            DeleteJK_NAME(strincheckid2);
                            ShowRobotMsg("Info", string.Format("机械手:{0},电芯1:{1}到位申请完成,清除InCheck校验接口记录", rb.robotnum + rb.robotName, rb.barcode1));
                            ShowRobotMsg("Info", string.Format("机械手:{0},电芯2:{1}到位申请完成,清除InCheck校验接口记录", rb.robotnum + rb.robotName, rb.barcode2));
                            DeleteJK_NAME(strid3);
                            DeleteJK_NAME(strid4);
                            ShowRobotMsg("Info", string.Format("机械手:{0},电芯3:{1}到位申请完成,清除校验接口记录", rb.robotnum + rb.robotName, rb.barcode3));
                            ShowRobotMsg("Info", string.Format("机械手:{0},电芯4:{1}到位申请完成,清除校验接口记录", rb.robotnum + rb.robotName, rb.barcode4));
                            DeleteJK_NAME(strincheckid3);
                            DeleteJK_NAME(strincheckid4);
                            ShowRobotMsg("Info", string.Format("机械手:{0},电芯1:{1}到位申请完成,清除InCheck校验接口记录", rb.robotnum + rb.robotName, rb.barcode1));
                            ShowRobotMsg("Info", string.Format("机械手:{0},电芯2:{1}到位申请完成,清除InCheck校验接口记录", rb.robotnum + rb.robotName, rb.barcode2));
                            TaskInfo[0] = "2";
                            cmd = RobotCommand.CheckResult;
                            _check_flag = true;
                        }
                    }
                    if (_check_flag)
                    {
                        string plcmsg = string.Empty;
                        for (int i = 1; i <= rb.cellNum; i++)
                        {
                            plcmsg += "第" + i + "个电芯的校验结果为：" + TaskInfo[i] + ";";
                        }
                        cmd = RobotCommand.CheckResult;
                        if (WriteRobotInfo("PutRobot", cmd, rb.robotnum.ToString(), TaskInfo, index, rb.cellNum * 2 + 1, rb.cellNum))
                        {
                            Byte[] writeResult = new Byte[rb.cellNum + 1];
                            //Byte[] writeResult = new Byte[rb.cellNum * 2];
                            /*for (int i = 0; i < rb.cellNum * 2; i++)
                            {
                                writeResult[i] = 0;
                            }*/
                            if (ReadRobotInfo(rb, index, rb.cellNum * 2, ref writeResult))
                            {
                                string cellResult = string.Empty;
                                for (int i = 1; i <= rb.cellNum; i++)
                                {
                                    // cellResult += "第" + i + "个电芯的校验结果为：" + (writeResult[2 * i - 2] * 256 + writeResult[2 * i - 1]) + ";";
                                    cellResult += "第" + i + "个电芯的校验结果为：" + (writeResult[i] * 256 + writeResult[i + 1]) + ";";

                                }
                                ShowRobotMsg("Info", string.Format("机械手:{0},命令:{1}写入成功后,读取数据如下:{2}！", rb.robotnum + rb.robotName, cmd, cellResult));
                            }

                            ShowRobotMsg("Info", string.Format("机械手:{0},命令:{1}写入成功,数据如下：{2}！", rb.robotnum + rb.robotName, cmd, plcmsg));
                        }
                        else
                        {
                            ShowRobotMsg("Info", string.Format("机械手:{0},命令:{1}写入失败,数据如下：{2}！", rb.robotnum + rb.robotName, cmd, plcmsg));
                        }
                        _check_flag = false;
                    }
                }
                #endregion

                #region 二组电芯到位申请--NCXWD屏蔽不用--xjm
                if (rb.checkbarcodereading == 30 && rb.rbstate == 1)
                {
                    ShowRobotMsg("Info", string.Format("机械手:{0},条码到位申请，条码3为：{1}！", rb.robotnum + rb.robotName, rb.barcode3));
                    ShowRobotMsg("Info", string.Format("机械手:{0},条码到位申请，条码4为：{1}！", rb.robotnum + rb.robotName, rb.barcode4));
                    if (checkStatus == "1")
                    {
                        #region 判断电芯3与托盘内电芯的前13位是否一致
                        if (rb.traycode.Length > 10)
                        {
                            if (CheckCell(rb, rb.barcode3, "3", rb.traycode, ref TaskInfo[3]))
                            {
                                b_flag3 = true;
                            }
                        }
                        #endregion

                        #region 检测条码3与条码1前13位
                        if (rb.barcode3.Trim(' ').Length > 13)
                        {
                            if (rb.barcode3.Substring(0, 13) != rb.barcode1.Substring(0, 13) && !b_flag1 && !b_flag3)
                            {
                                ShowRobotMsg("Info", string.Format("机械手:{0},到位申请电芯3:{1}与电芯1:{2}前13位不一致.该电芯当NG处理", rb.robotnum + rb.robotName, rb.barcode3, rb.barcode1));
                                TaskInfo[3] = "2";
                                b_flag3 = true;
                            }
                        }
                        #endregion
                    }
                    if (!b_flag3)
                    {
                        if (Checkbarcodereading_check(rb, rb.barcode3, "3", rb.traycode, ref TaskInfo[3], ref strid3, ref strincheckid3))
                        {
                            b_flag3 = true;
                        }
                    }
                    if (checkStatus == "1")
                    {
                        #region 判断电芯4与托盘内电芯的前13位是否一致
                        if (rb.traycode.Length > 10)
                        {
                            if (CheckCell(rb, rb.barcode4, "4", rb.traycode, ref TaskInfo[4]))
                            {
                                b_flag4 = true;
                            }
                        }
                        #endregion
                        #region 检测条码4与条码1前13位
                        if (rb.barcode4.Trim(' ').Length > 13)
                        {
                            if (rb.barcode4.Substring(0, 13) != rb.barcode1.Substring(0, 13) && !b_flag1 && !b_flag4)
                            {
                                ShowRobotMsg("Info", string.Format("机械手:{0},到位申请电芯4:{1}与电芯1:{2}前13位不一致.该电芯当NG处理", rb.robotnum + rb.robotName, rb.barcode4, rb.barcode1));
                                TaskInfo[4] = "2";
                                b_flag4 = true;
                            }
                        }
                        #endregion
                    }
                    if (!b_flag4)
                    {
                        if (Checkbarcodereading_check(rb, rb.barcode4, "4", rb.traycode, ref TaskInfo[4], ref strid4, ref strincheckid4))
                        {
                            b_flag4 = true;
                        }
                    }
                    if (b_flag3 && b_flag4)
                    {
                        if (rb.barcode4 == rb.barcode3 && rb.barcode3.Length >= 24 && rb.barcode4.Length >= 24)
                        {
                            ShowRobotMsg("Info", string.Format("机械手:{0},到位申请电芯3:{3},电芯4:{4}有多个条码一致.都当NG处理", rb.robotnum + rb.robotName, rb.barcode1, rb.barcode2, rb.barcode3, rb.barcode4));
                            TaskInfo[3] = "2";
                            TaskInfo[4] = "2";
                        }
                        index = 20;
                        Task.Run(() => DeleteJK_NAME(strid3));
                        Task.Run(() => DeleteJK_NAME(strid4));
                        ShowRobotMsg("Info", string.Format("机械手:{0},电芯3:{1}到位申请完成,清除校验接口记录", rb.robotnum + rb.robotName, rb.barcode3));
                        ShowRobotMsg("Info", string.Format("机械手:{0},电芯4:{1}到位申请完成,清除校验接口记录", rb.robotnum + rb.robotName, rb.barcode4));
                        TaskInfo[0] = "4";
                        cmd = RobotCommand.CheckResult;
                        _check_flag = true;
                    }
                    if (_check_flag)
                    {
                        string plcmsg = string.Empty;
                        for (int i = 3; i <= 4; i++)
                        {
                            plcmsg += "第" + i + "个电芯的校验结果为：" + TaskInfo[i] + ";";
                        }
                        cmd = RobotCommand.CheckResult;
                        if (WriteRobotInfo("PutRobot", cmd, rb.robotnum.ToString(), TaskInfo, index, rb.cellNum * 2 + 1, rb.cellNum))
                        {
                            Byte[] writeResult = new Byte[rb.cellNum * 2];
                            if (ReadRobotInfo(rb, index, rb.cellNum * 2, ref writeResult))
                            {
                                string cellResult = string.Empty;
                                for (int i = 3; i <= 4; i++)
                                {
                                    cellResult += "第" + i + "个电芯的校验结果为：" + (writeResult[2 * i - 6] * 256 + writeResult[2 * i - 5]) + ";";
                                }
                                ShowRobotMsg("Info", string.Format("机械手:{0},命令:{1}写入成功后,读取数据如下:{2}！", rb.robotnum + rb.robotName, cmd, cellResult));
                            }

                            ShowRobotMsg("Info", string.Format("机械手:{0},命令:{1}写入成功,数据如下：{2}！", rb.robotnum + rb.robotName, cmd, plcmsg));
                        }
                        else
                        {
                            ShowRobotMsg("Info", string.Format("机械手:{0},命令:{1}写入失败,数据如下：{2}！", rb.robotnum + rb.robotName, cmd, plcmsg));
                        }
                        _check_flag = false;
                    }
                }
                #endregion
            }
            catch (Exception ex)
            {
                ShowRobotMsg("Info", string.Format("机械手:{0},报错:{1}！", rb.robotnum + rb.robotName, ex));
            }
        }
        /// <summary>
        ///  校验校验电芯与托盘内电芯前13位
        /// </summary>
        /// <param name="rb"></param>
        /// <param name="itembarcode">电芯条码</param>
        /// <param name="count">校验电芯位置</param>
        /// <returns></returns>
        private bool CheckCell(RobotInfo rb, string itembarcode, string count, string barcode, ref string TaskInfo)
        {
            string fristItemcode = string.Empty;
            if (itembarcode.Contains("ERROR") || itembarcode.Length < 24)//原本电池类型cellbarcodetype
            {
                ShowRobotMsg("Info", string.Format("机械手:{0},校验扫码器{1}号位,电芯:{2},条码ERROR或长度小于24,被NG处理", rb.robotnum + rb.robotName, count, itembarcode));
                TaskInfo = "2";
                return true;
            }
            else
            {
                if (FirstItemcodeInfo.ContainsKey(barcode))
                {
                    if (FirstItemcodeInfo[barcode].Length > 13)
                    {
                        if (itembarcode.Substring(0, 13) != FirstItemcodeInfo[barcode].Substring(0, 13))
                        {
                            TaskInfo = "2";
                            ShowRobotMsg("Info", string.Format("机械手:{0},第{3}个电芯:{1}前13位与托盘:{2}内电芯条码前13位不一致", rb.robotnum + rb.robotName, itembarcode, barcode, count));
                            return true;
                        }
                    }
                    else
                        FirstItemcodeInfo.Remove(barcode);
                }
                else
                {
                    if (checkCellIsSame(barcode, ref fristItemcode)) //返回托盘内靠前位置的1个条码 
                    {
                        if (fristItemcode.Length > 13)
                        {
                            if (itembarcode.Substring(0, 13) != fristItemcode.Substring(0, 13))
                            {
                                FirstItemcodeInfo.Add(barcode, fristItemcode);//需在绑盘后去除
                                TaskInfo = "2";
                                ShowRobotMsg("Info", string.Format("机械手:{0},第{3}个电芯:{1}前13位与托盘:{2}内电芯条码前13位不一致", rb.robotnum + rb.robotName, itembarcode, barcode, count));
                                return true;
                            }
                        }
                    }
                }
            }
            return false;
        }
        /// <summary>
        /// 组盘业务处理
        /// </summary>
        /// <param name="rb"></param>
        private void Put(RobotInfo rb)
        {
            try
            {
                RobotCommand cmd = RobotCommand.None;
                List<string> lst = new List<string>();
                Dictionary<int, string> errorBarcode = new Dictionary<int, string>();
                Dictionary<int, string> sameBarcode = new Dictionary<int, string>();
                StringBuilder strSameTemp = new StringBuilder();
                StringBuilder strErrorTemp = new StringBuilder();
                string containerbarcode = string.Empty;
                lst.Clear();
                string strid1 = "";
                string strincheckid1 = "";
                int index = 0;
                int length = 0;
                int newCellCount = 0;
                int CellCount = 0;

                if (barcodeCheck.Equals("1"))
                {
                    CheckCellType(rb.robotnum);
                    if (celllen < 1) celllen = 30;
                }
                else
                {//不开启条码校验时,条码长度和电控最长保持一致
                    celllen = 30;
                }
                foreach (var postion in rb.positions)
                {
                    if (postion == "1")
                    {
                        newCellCount++;
                    }
                }
                string[] TaskInfo1 = rb.positions.ToArray();
                // String[] StaStationInfo = new string[30];
                // StaStationInfo = converyPLC.ReadStaInfo(rb.stationno, 0);

                String[] StaStationInfo = converyPLC.ReadStaInfo(rb.stationno, 0);
                string PalletCode = StaStationInfo[2].Trim(' ');
                rb.traycode = PalletCode;
                if (rb.rbstate == 3)
                {
                    string message = string.Empty;
                    if (rb.alarmCode > 0)
                    {
                        if (RobotAlarm.ContainsKey(rb.alarmCode.ToString()))
                        {
                            message = RobotAlarm[rb.alarmCode.ToString()];
                        }
                        else
                        {
                            message = "未知故障!";
                        }
                        QueueSpeech.AddQueue("机械手绑盘" + rb.stationno + "站台" + message);
                        ShowRobotMsg("Alarm", string.Format("{0}机械手报警,报警信息为:{1}", rb.name, message));
                    }
                }
                #region 绑定托盘
                if ((rb.pickbarcodereading == 1 || newCellCount > 0 || rb.pickbarcodereading == 4 || rb.pickbarcodereading == 5) && rb.rbstate == 1)
                {
                    if (string.IsNullOrEmpty(PalletCode))
                    {
                        ShowRobotMsg("Info", string.Format("机械手:{0},托盘条码长度非法或为空！", rb.robotnum));
                        return;//托盘条码为空
                    }
                    if (rb.BarCodeList.Count < 1)
                    {
                        ShowRobotMsg("Info", string.Format("机械手:{0},托盘:{1}没有电芯数据", rb.robotnum, PalletCode));
                        return;
                    }
                    if (rb.BarCodeList.Count > rb.cellNum)
                    {
                        ShowRobotMsg("Info", string.Format("机械手:{0},托盘:{1}", rb.robotnum, PalletCode + "电芯数据大于" + rb.cellNum + "条."));
                        return;
                    }

                    for (int i = 0; i < rb.BarCodeList.Count; i++)
                    {
                        string barcode1lth = rb.BarCodeList[i].Trim('\0');
                        if (!lst.Contains(barcode1lth))
                        {
                            lst.Add(barcode1lth);
                            if ((barcode1lth.Contains("ERROR")) || barcode1lth == "Empty")
                            {
                                errorBarcode.Add(i + 1, barcode1lth);
                                strErrorTemp.Append("位置:" + (i + 1) + ",电芯:" + barcode1lth);
                            }
                            if (!barcode1lth.Contains("ERROR") && barcode1lth != "Empty" && barcode1lth.Length > 10)
                            {
                                CellCount++;
                            }
                        }
                        else
                        {
                            if (barcode1lth != "Empty" && barcode1lth.Trim(' ') != "")
                            {
                                sameBarcode.Add(i + 1, barcode1lth);
                                strSameTemp.Append("位置:" + (i + 1) + ",电芯:" + barcode1lth);
                            }
                        }
                    }
                    if (CellCount != rb.rbnumber)
                    {
                        ShowRobotMsg("Info", string.Format("机械手:{0},托盘:{1}数据不一致!有效电芯数量:{2},装盘数量:{3}", rb.robotnum, PalletCode, CellCount, rb.rbnumber));
                        if (errorBarcode.Keys.Count > 0)
                        {
                            ShowRobotMsg("Info", string.Format("机械手:{0}收到错误条码,电芯条码为:{1}", rb.robotnum, strErrorTemp));
                        }
                        if (sameBarcode.Keys.Count > 0)
                        {
                            ShowRobotMsg("Info", string.Format("机械手:{0}收到重复条码,电芯条码为:{1}", rb.robotnum, strSameTemp));
                        }
                        return;
                    }
                    for (int i = 0; i < rb.positions.Count; i++)
                    {
                        if (rb.positions[i] == "1")
                        {
                            string barcode1lth = rb.BarCodeList[i].Trim('\0').Trim(' ').Trim();
                            if ((barcode1lth.Contains("ERROR")) && barcode1lth == "Empty")
                            {
                                ShowRobotMsg("Info", string.Format("机械手:{0},托盘:{1},位置:{2},写入normal电池条码失败,该位置没有电芯条码！", rb.robotnum, PalletCode, int.Parse(rb.positions[i])));
                                return;
                            }
                            if (barcode1lth.Length < 12)
                            {
                                ShowRobotMsg("Info", string.Format("机械手:{0},托盘:{1},位置:{2},写入normal电池条码失败,该电芯条码长度异常,不足12位!！", rb.robotnum, PalletCode, int.Parse(rb.positions[i])));
                                return;
                            }
                            if (getitemcodenum(PalletCode, barcode1lth, i + 1) > 0)
                            {
                                ShowRobotMsg("Info", string.Format("机械手:{0},托盘:{1},电芯:{2},写入normal电池条码失败,该电芯在本托盘内已有绑盘记录！", rb.robotnum, PalletCode, barcode1lth));
                                return;
                            }
                        }
                    }
                    if (MESStatus == "1")
                    {
                        for (int i = 0; i < rb.positions.Count; i++)
                        {
                            if (rb.positions[i] == "1"|| (rb.positions[i]=="0"&&rb.BarCodeList[i].Trim('\0').Trim(' ').Trim().Length>21))
                            {
                                //复测组盘需要检查电芯是否能绑定托盘。校验失败，WCS回复机械手电芯NG
                                if (rb.stationtype == 4)
                                {
                                    bool check_flag = false;
                                    string[] TaskInfo = { "0" };
                                    if (ANDcell_check(rb, rb.BarCodeList[i], ref strid1) && ANDcell_InStationCheck(rb, rb.BarCodeList[i], ref strincheckid1))
                                    {
                                        TaskInfo[0] = "1";
                                        check_flag = true;
                                    }
                                    else
                                    {
                                        ShowRobotMsg("Info", string.Format("机械手:{0},电芯:{1},添加jk_mes表FittingCheckForCell接口数据失败！", rb.robotnum + rb.robotName, rb.BarCodeList[i]));
                                        return;
                                    }

                                    if (check_flag)
                                    {
                                        for (int k = 0; k < 10000; k++)
                                        {
                                            if (Checkbarcodereading_check(rb, rb.BarCodeList[i], "1", PalletCode, ref TaskInfo[0], ref strid1, ref strincheckid1))
                                            {
                                                ShowRobotMsg("Info", string.Format("机械手:{0},检查电芯是否能绑定托盘MES次数:{1},成功！", rb.robotnum + rb.robotName, k));
                                                DeleteJK_NAME(strid1);
                                                ShowRobotMsg("Info", string.Format("机械手:{0},电芯:{1}三坐标组盘,清除校验接口记录", rb.robotnum + rb.robotName, rb.BarCodeList[i]));
                                                DeleteJK_NAME(strincheckid1);
                                                ShowRobotMsg("Info", string.Format("机械手:{0},电芯:{1}三坐标组盘,清除InCheck校验接口记录", rb.robotnum + rb.robotName, rb.BarCodeList[i]));
                                                break;
                                            }
                                            k++;
                                        }
                                        if (TaskInfo[0] == "2")
                                        {
                                            TaskInfo1[i] = "3";
                                            string[] plcstr = new string[1] { "" };
                                            plcstr[0] = TaskInfo1[i];
                                            _ExecuteResult = WriteRobotInfo("PutRobot", RobotCommand.BindResult, rb.robotnum, plcstr, i * 2 + 20, 2, rb.cellNum);
                                            ShowRobotMsg("Info", string.Format("机械手:{0}通知夹爪上电芯NG,WCS处理后回复结果:{1}.电芯条码:{2}！", rb.robotnum + rb.robotName, _ExecuteResult ? "成功" : "失败", rb.BarCodeList[i]));
                                            return;
                                        }
                                    }
                                }

                                if (UpdateCellStatus(PalletCode, i + 1, rb.BarCodeList[i]))
                                {
                                    ShowRobotMsg("Info", string.Format("机械手:{0},托盘:{1},电芯:{2},写入wcs_itemcode表normal电池条码成功！", rb.robotnum + rb.robotName, PalletCode, rb.BarCodeList[i]));
                                    TaskInfo1[i] = "2";
                                    string[] plcstr = new string[1] { "" };
                                    plcstr[0] = TaskInfo1[i];
                                    _ExecuteResult = WriteRobotInfo("PutRobot", RobotCommand.BindResult, rb.robotnum, plcstr, i * 2 + 20, 2, rb.cellNum);
                                    ShowRobotMsg("Info", string.Format("机械手:{0}通知夹爪上电芯放入托盘完成,WCS处理后回复结果:{1}.电条码:{2}！", rb.robotnum + rb.robotName, _ExecuteResult ? "成功" : "失败", rb.BarCodeList[i]));
                                }
                                else
                                {
                                    ShowRobotMsg("Info", string.Format("机械手:{0},托盘:{1},电芯:{2},写入wcs_itemcode表normal电池条码失败！", rb.robotnum + rb.robotName, PalletCode, rb.BarCodeList[i]));
                                    return;
                                }
                            }
                        }

                        //状态写入PLC
                        //_ExecuteResult = WriteRobotInfo("PutRobot", RobotCommand.BindResult, rb.robotnum, TaskInfo1, i * 2 + 20, 2, rb.cellNum);
                        //ShowRobotMsg("Info", string.Format("机械手:{0}通知夹爪上电芯放入托盘完成,WCS处理后回复结果:{1}.电条码:{2}！", rb.robotnum + rb.robotName, _ExecuteResult ? "成功" : "失败", rb.BarCodeList[i]));




                        //绑盘完成调用绑盘接口
                        if (rb.pickbarcodereading == 1|| rb.pickbarcodereading == 4)
                        {
                            int bindNum1 = 0;

                            foreach (var taskinfo in TaskInfo1)
                            {
                                if (taskinfo == "2")
                                {
                                    bindNum1++;
                                }
                            }
                            if (bindNum1 == rb.rbnumber)
                            {
                                if (GetGongYi(rb.stationno, rb.ZoneId, "FittingBinding", LineCode, ref mes_site, ref operation_revision, ref mes_resource, ref mesuser, ref _gongyiID))
                                {
                                    int countjk = CheckJK_MES("", "FittingBinding", PalletCode, 0, ref containerbarcode);
                                    if (countjk == 0)
                                    {
                                        if (AddJK_CellInfo(rb.ZoneId, rb.ZoneCode, PalletCode, _gongyiID, "0", "FittingBinding", "MES", "WCS", "1", mes_site, operation_revision, mes_resource, "", "20", "COLUMN-FIRST", "", mesuser, ref strid1))
                                        {
                                            ShowRobotMsg("Info", string.Format("机械手:{0},托盘:{1}调用MES电池绑定接口,WCS处理成功！", rb.robotnum, PalletCode));
                                        }
                                        else
                                        {
                                            /*if (UpdateCellStatus(PalletCode, i + 1, "WCS" + rb.BarCodeList[i]))
                                              {
                                                  ShowRobotMsg("Info", string.Format("机械手:{0},托盘{1}添加电芯:{2}绑盘接口失败,将该电芯回滚至假电芯", rb.robotnum + rb.robotName, PalletCode, rb.BarCodeList[i]));
                                              }*/
                                            ShowRobotMsg("Info", string.Format("机械手:{0},托盘:{1}调用MES电池绑定接口,WCS处理失败！", rb.robotnum + rb.robotName, PalletCode));
                                            return;
                                        }
                                    }
                                    /*
                                    else
                                    {
                                        ShowRobotMsg("Info", string.Format("机械手:{0},托盘:{1}有绑盘接口记录！请先清除该电芯的接口记录!", rb.robotnum + rb.robotName, containerbarcode));
                                        return;
                                    }*/
                                }
                                else
                                {
                                    ShowRobotMsg("Info", string.Format("机械手:{0},站台:{1}没有配置工艺", rb.robotnum + rb.robotName, rb.stationno));
                                    return;
                                }
                            }
                        }
                    }
                    else
                    {
                        for (int i = 0; i < rb.positions.Count; i++)
                        {
                            if (rb.positions[i] == "1")
                            {
                                if (UpdateCellStatus(PalletCode, i + 1, rb.BarCodeList[i]))
                                {
                                    ShowRobotMsg("Info", string.Format("机械手:{0},托盘:{1},电芯:{2},写入wcs_itemcode表normal电池条码成功！", rb.robotnum + rb.robotName, PalletCode, rb.BarCodeList[i]));
                                    TaskInfo1[i] = "2";
                                    string[] plcstr = new string[1] { "" };
                                    plcstr[0] = TaskInfo1[i];
                                    _ExecuteResult = WriteRobotInfo("PutRobot", RobotCommand.BindResult, rb.robotnum, plcstr, i * 2 + 20, 2, rb.cellNum);
                                    ShowRobotMsg("Info", string.Format("机械手:{0}通知夹爪上电芯放入托盘完成,WCS处理后回复结果:{1}！", rb.robotnum + rb.robotName, _ExecuteResult ? "成功" : "失败"));
                                }
                                else
                                    ShowRobotMsg("Info", string.Format("机械手:{0},托盘:{1},电芯:{2},写入wcs_itemcode表normal电池条码失败！", rb.robotnum + rb.robotName, PalletCode, rb.BarCodeList[i]));
                            }
                        }
                        ShowRobotMsg("Info", string.Format("MES离线装盘成功！"));
                    }
                    if (rb.pickbarcodereading == 1)
                    {
                        int bindNum = 0;
                        string message = "";
                        foreach (var taskinfo in TaskInfo1)
                        {
                            if (taskinfo == "2")
                            {
                                bindNum++;
                            }
                        }
                        if (bindNum == rb.cellNum && bindNum == rb.rbnumber)
                        {
                            if (MESStatus == "1")
                            {
                                if (!CheckBindResult(PalletCode, "FittingBinding"))
                                {
                                    ShowRobotMsg("Info", string.Format("机械手:{0},托盘:{1}等待全部电芯返回绑盘结果", rb.robotnum + rb.robotName, PalletCode));
                                    return;
                                }
                            }
                        }
                        else
                        {
                            ShowRobotMsg("Info", string.Format("机械手:{0},托盘:{1}内WCS已处理电芯为:{2}个.装盘电芯:{3}个", rb.robotnum + rb.robotName, PalletCode, bindNum, rb.rbnumber));
                            return;
                        }
                    }
                    if (rb.pickbarcodereading == 4)
                    {
                        ShowRobotMsg("Info", string.Format("机械手:{0}申请强制出盘,托盘:{1}", rb.robotnum + rb.robotName, PalletCode));
                        int bindNum = 0;
                        string message = "";
                        foreach (var taskinfo in TaskInfo1)
                        {
                            if (taskinfo == "2")
                            {
                                bindNum++;
                            }
                        }
                        if (bindNum == rb.rbnumber && bindNum > 0)
                        {
                            if (MESStatus == "1")
                            {
                                if (!CheckBindResult(PalletCode, "FittingBinding"))
                                {
                                    ShowRobotMsg("Info", string.Format("机械手:{0},托盘:{1}等待全部电芯返回绑盘结果", rb.robotnum + rb.robotName, PalletCode));
                                    return;
                                }
                            }
                            else
                            {
                                ShowRobotMsg("Info", string.Format("机械手:{0},托盘:{1}内WCS已处理电芯为:{2}个.装盘电芯:{3}个", rb.robotnum + rb.robotName, PalletCode, bindNum, rb.rbnumber));
                                return;
                            }
                        }
                    }
                    if (rb.pickbarcodereading == 1 || rb.pickbarcodereading == 4)
                    {
                        int count = getCountByBarcode(PalletCode);
                        if (count != rb.rbnumber)
                        {
                            ShowRobotMsg("Info", string.Format("机械手:{0},托盘:{1}组盘完成,装盘电芯:{2},WCS绑定电芯:{3}", rb.robotnum + rb.robotName, PalletCode, rb.rbnumber, count));
                            return;
                        }
                        _pick_flag = true;
                    }
                    #region 强制剔除
                    if (rb.pickbarcodereading == 5)
                    {
                        string exceptionstation = string.Empty;
                        if (getExceptionTostation(rb.stationno, ref exceptionstation))
                        {
                            if (converyPLC.Write(STACommand.ClearToStation, new string[2] { rb.stationno, exceptionstation }, rb.stationno, 6, 2))
                            {
                                if (UpdateItempalletTostation(PalletCode, exceptionstation))
                                {
                                    _pick_flag = true;
                                    ShowRobotMsg("Info", string.Format("机械手:{0}申请托盘:{2}强制剔除,WCS将目标地址更新为:{1}！", rb.robotnum + rb.robotName, exceptionstation, PalletCode));
                                }
                            }
                        }
                    }
                    #endregion
                    if (_pick_flag)
                    {
                        FirstItemcodeInfo.Remove(rb.traycode);
                        string[] plcstr = new string[1] { "" };
                        plcstr[0] = "2";
                        cmd = RobotCommand.completePut;
                        _ExecuteResult = WriteRobotInfo("PutRobot", cmd, rb.robotnum, plcstr, index, length, rb.cellNum);
                        ShowRobotMsg("Info", string.Format("机械手:{0}申请托盘装盘完成,WCS处理后回复结果:{1}！", rb.robotnum + rb.robotName, _ExecuteResult ? "成功" : "失败"));
                        _pick_flag = false;
                    }
                }
                #endregion
            }
            catch (Exception ex)
            {
                ShowRobotMsg("Info", string.Format("机械手:{0},报错:{1}！", rb.robotnum + rb.robotName, ex));
            }
        }
        /// <summary>
        /// 读取站台的托盘条码与目标站台
        /// </summary>
        /// <param name="station">需要查询的站台</param>
        /// <param name="?"></param>
        /// <returns></returns>
        public string ReadbarcodeAndToStationInfo(string station, ref string toStation)
        {
            string barcode = "";
            if (!string.IsNullOrEmpty(station))
            {
                String[] StaStationInfo = converyPLC.ReadStaInfo(station);//读取复测工位站台信息
                barcode = StaStationInfo[2];//获取托盘条码
                toStation = StaStationInfo[5];//获取目标站台
            }
            return barcode;
        }

        /// <summary>
        /// 拆盘业务处理
        /// </summary>
        /// <param name="rb"></param>
        private void Pick(RobotInfo rb)
        {
            try
            {
                string[] TaskInfo = new string[rb.cellNum + 1];
                string[] PalletCodeinfo = new string[rb.cellNum * 2];
                string[] itembarcode = new string[rb.cellNum];
                RobotCommand cmd = RobotCommand.None;
                int index = 0;
                int length = 1;
                string PalletCode = "";//拆盘工位上的托盘条码
                bool rb_falg = false;
                string strInfo = "";
                string stationno = "";
                for (int i = 0; i < rb.cellNum; i++)
                {
                    TaskInfo[i] = "";
                }
                stationno = rb.stationno;
                String[] StaStationInfo = converyPLC.ReadStaInfo(stationno);//读取当前拆盘工位的信息
                PalletCode = StaStationInfo[2].Trim(' ');//获取托盘条码     
                rb.traycode = PalletCode;
                #region 解绑电芯
                if (rb.rbstate == 3)
                {
                    string message = string.Empty;
                    if (rb.alarmCode > 0)
                    {
                        if (RobotAlarm.ContainsKey(rb.alarmCode.ToString()))
                        {
                            message = RobotAlarm[rb.alarmCode.ToString()];
                        }
                        else
                        {
                            message = "未知故障!";
                        }
                        QueueSpeech.AddQueue("机械手解绑" + rb.stationno + "站台" + message);
                        ShowRobotMsg("Alarm", string.Format("{0}机械手报警,报警信息为:{1}", rb.name, message));
                    }
                }

                if (rb.trayreading == 1 && rb.rbstate == 1)//读取机器人是否有拆盘请求
                {
                    if (string.IsNullOrEmpty(PalletCode))
                    {
                        ShowRobotMsg("Info", string.Format("机械手:{0},托盘条码长度非法或为空！", rb.robotnum + rb.robotName));
                        return;//托盘条码为空
                    }
                    bool flag = false;
                    string[] cellnginfo;
                    string msg = "";
                   /* if (rb.zonecode == "A")
                    {
                        cellnginfo = GetCellNGInfo(PalletCode, rb.cellNum);
                    }
                    else*/ 
                    if (rb.stationno == "1282" || rb.stationno == "1285" || rb.stationno == "2567" || rb.stationno == "2564")
                    {
                        cellnginfo = GetCellOKInfo(PalletCode, rb.cellNum);
                    }
                    else
                    {
                        string operation = string.Empty;
                        operation = getOperation(PalletCode); //根据托盘获取上个测试工艺
                        cellnginfo = GetCellNGInfoFR(PalletCode, rb.cellNum, operation);
                    }//读取下发机械手电池信息
                    if (cellnginfo == null || string.IsNullOrEmpty(cellnginfo[0]))
                    {
                        ShowRobotMsg("Info", string.Format("机械手:{0},获取:{1}测试结果失败！", rb.robotnum + rb.robotName, PalletCode));
                        return;
                    }
                    if (cellnginfo.Length == rb.cellNum * 2)
                    {
                        if (rb.relaseMode == "2")  //表示单电芯解绑
                        {
                            string message = string.Empty;
                            for (int i = 0; i < rb.cellNum; i++)
                            {
                                if (cellnginfo[i] != "1" && cellnginfo[i + rb.cellNum].Substring(0, 3) != "MES" && cellnginfo[i + rb.cellNum].Substring(0, 3) != "WCS") // MES开头表示MES已解绑
                                {
                                    string result = CheckExistsCell(ref flag, ref strid, ref message, WareHouseID, "", "FittingUnBinding", cellnginfo[i + rb.cellNum]);
                                    if (!flag)
                                    {
                                        if (GetGongYi(rb.stationno, rb.ZoneId, "FittingUnBinding", LineCode, ref mes_site, ref operation_revision, ref mes_resource, ref mesuser, ref _gongyiID))
                                        {
                                            string strid = "";
                                            if (AddJK_CellInfo(rb.ZoneId, rb.ZoneCode, PalletCode, _gongyiID, "0", "FittingUnBinding", "MES", "WCS", "1", mes_site, operation_revision, mes_resource, cellnginfo[i + rb.cellNum], (i + 1).ToString(), "COLUMN-FIRST", "1", mesuser, ref strid))
                                                ShowRobotMsg("Info", string.Format("机械手:{0},电芯：{1},调用单电芯接口，WCS处理成功！", rb.robotnum + rb.robotName, cellnginfo[i + rb.cellNum]));
                                            else
                                                ShowRobotMsg("Info", string.Format("机械手:{0},电芯：{1},调用单电芯接口，WCS处理失败！", rb.robotnum + rb.robotName, cellnginfo[i + rb.cellNum]));
                                        }
                                        else
                                        {
                                            ShowRobotMsg("Info", string.Format("机械手:{0},站台:{1}没有配置工艺", rb.robotnum + rb.robotName, rb.stationno));
                                            return;
                                        }
                                    }
                                }
                            }
                            if (CheckBindResult(PalletCode, "FittingUnBinding"))
                            {
                                cmd = RobotCommand.PickCommand;
                                rb_falg = true;
                                for (int j = 0; j < rb.cellNum; j++)
                                {
                                    //TaskInfo[j] = cellnginfo[j];
                                    PalletCodeinfo[j] = cellnginfo[j];//添加
                                    strInfo += "位置：" + (j + 1) + "结果：" + cellnginfo[j];
                                }

                                for (int j = rb.cellNum; j < rb.cellNum * 2; j++)
                                {
                                    //TaskInfo[j] = cellnginfo[j];
                                    PalletCodeinfo[j] = cellnginfo[j];//添加
                                    strInfo += "位置：" + (j + 1) + "结果：" + cellnginfo[j];
                                }

                            }
                            else
                            {
                                ShowRobotMsg("Info", string.Format("机械手:{0},托盘：{1}，等待MES返回所有电芯解绑成功信号！", rb.robotnum + rb.robotName, PalletCode));
                                return;
                            }
                        }
                        else
                        {
                            string result = CheckExistsRelease(ref flag, ref msg, rb.ZoneId, PalletCode, "FittingUnBinding");
                            if (!flag)//查询是否已经解绑
                            {
                                if (GetGongYi(rb.stationno, rb.ZoneId, "FittingUnBinding", LineCode, ref mes_site, ref operation_revision, ref mes_resource, ref mesuser, ref _gongyiID))
                                {
                                    string strid = "";
                                    //  if (AddJK_CellInfo(rb.ZoneId, "S", PalletCode, _gongyiID, "0", "releaseTrayId", "MES", "WCS", "1", mes_site, operation_revision, "", "", "", "", "0", mesuser, ref strid))
                                    if (AddJK_CellInfo(rb.ZoneId, "S", PalletCode, _gongyiID, "0", "FittingUnBinding", "MES", "WCS", "1", mes_site, operation_revision, mes_resource, "", "", "", "0", mesuser, ref strid))
                                        ShowRobotMsg("Info", string.Format("机械手:{0},托盘:{1},调用MES解绑接口,WCS处理成功！", rb.robotnum + rb.robotName, PalletCode));
                                    else
                                        ShowRobotMsg("Info", string.Format("机械手:{0},托盘:{1},调用MES解绑接口,WCS处理失败！", rb.robotnum + rb.robotName, PalletCode));
                                }
                                else
                                {
                                    ShowRobotMsg("Info", string.Format("机械手:{0},站台:{1}没有配置工艺", rb.robotnum + rb.robotName, rb.stationno));
                                    return;
                                }
                            }
                            else
                            {
                                //string result = "0";
                                if (result == "0")//取解绑成功信号
                                {
                                    cmd = RobotCommand.PickCommand;
                                    rb_falg = true;
                                    for (int j = 0; j < rb.cellNum * 2; j++)
                                    {
                                        if (j < rb.cellNum)
                                        {
                                            TaskInfo[j] = cellnginfo[j];
                                            strInfo += "位置:" + (j + 1) + "结果:" + TaskInfo[j];
                                        }
                                        PalletCodeinfo[j] = cellnginfo[j];
                                    }
                                }
                                else
                                {
                                    if (!string.IsNullOrEmpty(result))
                                        ShowRobotMsg("Info", string.Format("机械手:{0},托盘:{1},解绑失败！", rb.robotnum + rb.robotName, PalletCode));
                                    else
                                        ShowRobotMsg("Info", string.Format("机械手:{0},托盘:{1},等待MES解绑！", rb.robotnum + rb.robotName, PalletCode));
                                }
                            }
                        }
                    }
                }
                if (rb.trayreading == 2 && rb.rbstate == 1)//机器人在拆盘过程
                {
                    for (int i = 0; i < rb.ResultList.Count(); i++)
                    {
                        if (i == 12 || i == 16 || i == 17 || i == 18)
                        { }
                        if (rb.ResultList[i] == "10")  //表示机械手已拆
                        {
                            if (UpdateItembarcode(PalletCode, i + 1, rb.BarCodeList[i], rb.robotName))
                            {
                                string[] plcstr = new string[1] { "" };
                                plcstr[0] = "11";
                                _ExecuteResult = WriteRobotInfo("PutRobot", RobotCommand.BindResult, rb.robotnum, plcstr, i * 2 + 20, 2, rb.cellNum);
                                ShowRobotMsg("Info", string.Format("机械手:{0}通知托盘:{1},位置:{3},电芯:{4}已拆,WCS处理后回复结果:{2}！", rb.robotnum + rb.robotName, PalletCode, _ExecuteResult ? "成功" : "失败", i + 1, rb.BarCodeList[i]));
                            }
                            else
                            {
                                if (checkItembarcode(PalletCode, i + 1))  //检测电芯是否已经是假电芯
                                {
                                     string[] plcstr = new string[1] { "" };
                                     plcstr[0] = "11";
                                    _ExecuteResult = WriteRobotInfo("PutRobot", RobotCommand.BindResult, rb.robotnum, plcstr, i * 2 + 20, 2, rb.cellNum);
                                    ShowRobotMsg("Info", string.Format("机械手:{0}通知托盘:{1},位置:{3},电芯:{4}已拆,WCS处理后回复结果:{2}！", rb.robotnum + rb.robotName, PalletCode, _ExecuteResult ? "成功" : "失败", i + 1, rb.BarCodeList[i]));
                                }
                                else
                                {
                                    ShowRobotMsg("Info", string.Format("机械手:{0}通知托盘:{1},位置:{2},电芯:{3}已拆,WCS更新为假电芯失败!", rb.robotnum + rb.robotName, PalletCode, i + 1, rb.BarCodeList[i]));
                                    return;
                                }
                            }
                        }
                    }
                }
                if (rb.trayreading == 3 && rb.rbstate == 1)//读取机器人是否有拆盘完成请求
                {
                    int pickCount = 0;
                    bool pickflak = false;
                    foreach (var result in rb.ResultList)
                    {
                        if (result == "11")
                            pickCount++;
                    }
                    if (rb.relaseMode=="2")//挑选位判断是否需要挑选
                    {
                        pickflak = pickCellOKInfo(rb.traycode);
                    }
                    if ((pickCount == rb.rbpickcount && pickCount > 0) || pickflak)
                    {
                        cmd = RobotCommand.completePick;//拆盘完成回复信息
                        rb_falg = true;
                    }
                    else
                        ShowRobotMsg("Info", string.Format("机械手:{0},托盘:{1},已拆数量:{2}与WCS已处理数量:{3}不一致！", rb.robotnum + rb.robotName, PalletCode, rb.rbpickcount, pickCount));
                }
                #endregion             
                if (rb_falg)
                {
                    if (cmd != RobotCommand.None)
                    {
                        if (WriteRobotInfo("PickRobot", cmd, rb.robotnum, PalletCodeinfo, index, length, rb.cellNum))
                        {
                            if (cmd == RobotCommand.PickCommand)
                            {
                                ShowRobotMsg("Info", string.Format("机械手:{0},托盘:{1},命令:{2},电芯结果:{3},写入PLC成功！", rb.robotnum, PalletCode, RobotCommand.PickCommand, strInfo));
                            }
                            if (cmd == RobotCommand.completePick)
                            {
                                ShowRobotMsg("Info", string.Format("机械手:{0}通知WCS托盘:{1},拆盘完成WCS回复成功.", rb.robotnum + rb.robotName, PalletCode));
                            }
                            if (cmd == RobotCommand.ReWorkResponse)
                            {
                                ShowRobotMsg("Info", string.Format("机械手:{0}通知WCS托盘:{1},组盘完成WCS回复成功.", rb.robotnum + rb.robotName, PalletCode));
                            }
                        }
                        else
                        {
                            ShowRobotMsg("Info", string.Format("机械手:{0},托盘:{1},命令:{2},电芯结果:{3},写入PLC失败！", rb.robotnum + rb.robotName, PalletCode, TaskInfo[0], strInfo));
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                ShowRobotMsg("Info", string.Format("机械手:{0},报错:{1}！", rb.robotnum + rb.robotName, ex));
                throw ex;
            }
        }

        /// <summary>
        /// 码垛业务处理
        /// </summary>
        /// <param name="rb"></param>
        private void Stacking(RobotInfo rb)
        {
            try
            {
                string[] TaskInfo = new string[2] { "0", "0"};
                RobotCommand cmd = RobotCommand.None;
                bool b_flag1 = false;
                bool check1_flag = false;
                string strid1 = "";
                string fristItemcode = string.Empty;
                int index = 12;
                if (barcodeCheck.Equals("1"))
                {
                    CheckCellType(rb.robotnum);
                    if (celllen < 1) celllen = 14;
                }
                else
                {//不开启条码校验时,条码长度和电控最长保持一致
                    celllen = 14;
                }
                if (rb.rbstate == 3)
                {
                    string message = rb.rbstate == 3 ? "故障" : "手动";
                    QueueSpeech.AddQueue("机械手扫码枪" + rb.stationno + "站台" + message);
                }
                #region 单托盘扫码交互申请
                if (rb.inplacebarcodereading == 1 && rb.rbstate == 1)
                {
                    _inplace_flag = false;
                    ShowRobotMsg("Info", string.Format("机械手:{0},申请托盘扫码，托盘条码为：{1}！", rb.robotnum + rb.robotName, rb.barcode1));
                    if (rb.barcode1 == "ERROR"|| rb.barcode1.Length<9)
                    {
                        check1_flag = false;
                        ShowRobotMsg("Info", string.Format("机械手:{0},申请条码校验，条码非法，为：{1}！", rb.robotnum + rb.robotName, rb.barcode1));
                    }
                    else
                    {
                        if (AddTrayGradeInterface(rb, rb.barcode1, ref strid1))
                        {
                            check1_flag = true;
                        }
                    }
                    if (rb.cellNum == 1)
                    {
                        if (check1_flag)
                        {
                            TaskInfo[0] = "2";
                            _inplace_flag = true;
                        }
                    }
                    if (_inplace_flag)
                    {
                        string plcmsg = string.Empty;
                        plcmsg += rb.barcode1+"托盘分档接口回复信号：" + TaskInfo[0] + ";";
                        cmd = RobotCommand.ScanTrayCommand;
                        if (WriteRobotInfo("StackingRobot", cmd, rb.robotnum.ToString(), TaskInfo, index, rb.cellNum, rb.cellNum))
                        {
                            ShowRobotMsg("Info", string.Format("机械手:{0},命令:{1}写入成功,数据如下：{2}！", rb.robotnum + rb.robotName, cmd, plcmsg));
                        }
                        else
                        {
                            ShowRobotMsg("Info", string.Format("机械手:{0},命令:{1}写入失败,数据如下：{2}！", rb.robotnum + rb.robotName, cmd, plcmsg));
                        }
                        _inplace_flag = false;
                    }
                }
                #endregion

                #region 托盘码垛交互申请
                if (rb.checkbarcodereading == 1 && rb.rbstate == 1)
                {
                    ShowRobotMsg("Info", string.Format("机械手:{0},托盘到位申请，托盘条码为：{1}！", rb.robotnum + rb.robotName, rb.barcode1));
                    _check_flag = false;
                    if (!b_flag1)
                    {
                        if (CheckTrayGrade(rb, "1", rb.traycode, ref TaskInfo[1], ref strid1))
                        {
                            b_flag1 = true;
                        }
                    }
                    if (rb.cellNum == 1&& b_flag1)
                    {
                        index = 20;
                        DeleteJK_NAME(strid1);
                        ShowRobotMsg("Info", string.Format("机械手:{0},托盘1:{1}到位申请完成,清除MES托盘分档接口记录", rb.robotnum + rb.robotName, rb.barcode1));
                        TaskInfo[0] = "2";
                        cmd = RobotCommand.TrayGradeCommand;
                        _check_flag = true;

                    }
                    if (_check_flag)
                    {
                        string plcmsg = string.Empty;
                        for (int i = 1; i <= rb.cellNum; i++)
                        {
                            plcmsg += rb.traycode + "托盘档级为：" + TaskInfo[i] + ";";
                        }
                        cmd = RobotCommand.TrayGradeCommand;
                        if (WriteRobotInfo("StackingRobot", cmd, rb.robotnum.ToString(), TaskInfo, index, rb.cellNum, rb.cellNum))
                        {
                            /*Byte[] writeResult = new Byte[rb.cellNum + 1];
                            if (ReadRobotInfo(rb, index, rb.cellNum * 2, ref writeResult))
                            {
                                string cellResult = string.Empty;
                                for (int i = 1; i <= rb.cellNum; i++)
                                {
                                    cellResult += "第" + i + "个电芯的校验结果为：" + (writeResult[i] * 256 + writeResult[i + 1]) + ";";

                                }
                                ShowRobotMsg("Info", string.Format("机械手:{0},命令:{1}写入成功后,读取数据如下:{2}！", rb.robotnum + rb.robotName, cmd, cellResult));
                            }*/

                            ShowRobotMsg("Info", string.Format("机械手:{0},命令:{1}写入成功,数据如下：{2}！", rb.robotnum + rb.robotName, cmd, plcmsg));
                            if (DeleteItemdetail_Grade(rb.traycode))
                              ShowRobotMsg("Info", string.Format("机械手:{0},托盘1:{1}WCS回复码盘交互成功,清除MES托盘分档信息记录", rb.robotnum + rb.robotName, rb.traycode));
                        }
                        else
                        {
                            ShowRobotMsg("Info", string.Format("机械手:{0},命令:{1}写入失败,数据如下：{2}！", rb.robotnum + rb.robotName, cmd, plcmsg));
                        }
                        _check_flag = false;
                    }
                }
                #endregion
            }
            catch (Exception ex)
            {
                ShowRobotMsg("Info", string.Format("机械手:{0},报错:{1}！", rb.robotnum + rb.robotName, ex));
            }
        }

        private void ShowRobotMsg(string type, string Msg)
        {
            if (ShowRBMsg != null)
            {
                ShowRBMsg(type, Msg);
                RobotMsg robotMsg = new RobotMsg();
                robotMsg.type = type;
                robotMsg.Msg = Msg;
                var robotMsgString = Newtonsoft.Json.JsonConvert.SerializeObject(robotMsg);
                WebSocketHelper.SendMsgToRemotePoint("RobotMsg" + robotMsgString);
                if (type == "Info")
                {
                    robotlog.Info(Msg);
                }
                else
                    robotConnectlog.Info(Msg);
            }
        }

        private void ShowRobotStatus(object obj)
        {
            try
            {
                if (ShowRbStatus != null)
                {
                    if (obj is RobotInfo)
                    {
                        RobotInfo rb = (RobotInfo)obj;
                        if (rb.stationtype == 2 || rb.stationtype == 4 || rb.stationtype == 3)
                        {
                            rb.LstBattery.Clear();
                            for (int i = 1; i <= rb.cellNum; i++)
                            {
                                BatteryInfo battery = new BatteryInfo();
                                battery.BatteryCode = i > rb.BarCodeList.Count ? "" : rb.BarCodeList[i - 1];
                                battery.BatteryResult = i > rb.ResultList.Count ? "" : rb.ResultList[i - 1];
                                battery.Position = i;
                                rb.LstBattery.Add(battery);
                            }
                        }
                        ShowRbStatus(rb);
                        var robotInfoString = Newtonsoft.Json.JsonConvert.SerializeObject(rb);
                        WebSocketHelper.SendMsgToRemotePoint("RobotInfo" + robotInfoString);
                    }
                }
            }
            catch (Exception ex)
            {
                ShowRobotMsg("Info", string.Format("机械手:{0},报错:{1}！", "", ex));
                throw ex;
            }
        }

        private bool WriteRobotInfo(string robottype, RobotCommand cmd, string robotnum, string[] str, int index, int length, int cellNum)
        {
            return robotPLC.WriteRobotInfo(robottype, robotnum, cmd, str, index, length, cellNum);
        }
        private bool ReadRobotInfo(RobotInfo rb, int index, int length, ref Byte[] rbBuffer)
        {
            return robotPLC.ReadRobotInfo(rb, index, length, ref rbBuffer);
        }
    }
}
